<?php

namespace app\command\service;

use think\facade\Log;
use Workerman\Timer;
use Workerman\Worker;

class TongJiServer
{
    public static function start()
    {
        $task = new Worker();
        $task->count = 1;
        $task->name = 'pv collect';

        $task->onWorkerStart = function($task)
        {
            $db = new \Workerman\MySQL\Connection(env('database.hostname'),
                env('database.hostport', 3306), env('database.username'), env('database.password', ''), env('database.database', ''));

            /*************************************** 站长之家排名开始 ************************************************/
            $baiduPcUrl = 'https://apidatav2.chinaz.com/single/baidupc/keywordranking';
            $baiduMobileUrl = 'https://apidatav2.chinaz.com/single/baidumobile/keywordranking';
            $pc360Url = 'https://apidatav2.chinaz.com/single/sopc/keywordranking';
            $sogouMobileUrl = 'https://apidatav2.chinaz.com/single/sogoumobile/keywordranking';
            file_put_contents('./last_rum_time.log', time()); // 上次执行时间

            $info = $db->select('value')->from(env('database.prefix') . 'sys_setting')
                ->where('title="chinaz_token" and seller_id=1')->row();

            if (!empty($info)) {
                $token = $info['value'];
                Timer::add(3600, function () use ($db, $token, $baiduPcUrl, $baiduMobileUrl, $pc360Url, $sogouMobileUrl) {
                    if (date('H:i') >= '11:52' || date('H:i') < '11:53') {

                        $frequency = $db->select('value')->from(env('database.prefix') . 'sys_setting')
                            ->where('title="keywords_search_time" and seller_id=1')->row();
                        $lastRunTime = file_get_contents('./last_rum_time.log');
                        $canRun = false;
                        if ($frequency == 'week') {
                            if ((time() - $lastRunTime) / 86400 >= 7) {
                                $canRun = true;
                                file_put_contents('./last_rum_time.log', time());
                            }
                        } elseif($frequency == 'day' && (time() - $lastRunTime) >= 86400) {
                            $canRun = true;
                            file_put_contents('./last_rum_time.log', time());
                        } else {
                            $canRun = true;
                            file_put_contents('./last_rum_time.log', time());
                        }
                        Log::info('可执行状态：' . $canRun);
                        try {
                            if ($canRun) {
                                Log::info('执行统计开始' . $canRun);
                                $keywords = $db->select('id,name,url,website_id,seller_id')->from(env('database.prefix') . 'keyword')
                                    ->where('status=1 and is_del=1')->query();

                                foreach ($keywords as $key => $vo) {

                                    $updateData = [
                                        'baidu_pc' => 0,
                                        'baidu_mob' => 0,
                                        'three_pc' => 0,
                                        'sougou_mob' => 0
                                    ];

                                    // 百度PC
                                    $res = curlPost($baiduPcUrl, [
                                        'key' => $token,
                                        'domain' => $vo['url'],
                                        'keyword' => $vo['name'],
                                        'top100' => true
                                    ])['data'];

                                    Log::info($vo['name'] . ' 百度PC res>>>>>>>:' . $res);
                                    $res = json_decode($res, true);

                                    if (!empty($res['Result']['Ranks'])) {
                                        $rank = explode('-', $res['Result']['Ranks']['0']['RankStr']);
                                        $updateData['baidu_pc'] = ($rank[0] - 1) * 10 + $rank['1'];

                                        self::writeKeywordsQuery($db, $vo, $res, $rank, 'baidu_pc');
                                    }

                                    // 百度移动
                                    $res = curlPost($baiduMobileUrl, [
                                        'key' => $token,
                                        'domain' => $vo['url'],
                                        'keyword' => $vo['name']
                                    ])['data'];

                                    Log::info($vo['name'] . ' 百度移动 res>>>>>>>:' . $res);
                                    $res = json_decode($res, true);
                                    if (!empty($res['Result']['Ranks'])) {
                                        $rank = explode('-', $res['Result']['Ranks']['0']['RankStr']);
                                        $updateData['baidu_mob'] = ($rank[0] - 1) * 10 + $rank['1'];

                                        self::writeKeywordsQuery($db, $vo, $res, $rank, 'baidu_mob');
                                    }

                                    // 360pc
                                    $res = curlPost($pc360Url, [
                                        'key' => $token,
                                        'domain' => $vo['url'],
                                        'keyword' => $vo['name']
                                    ])['data'];

                                    Log::info($vo['name'] . ' 360pc res>>>>>>>:' . $res);
                                    $res = json_decode($res, true);
                                    if (!empty($res['Result']['Ranks'])) {
                                        $rank = explode('-', $res['Result']['Ranks']['0']['RankStr']);
                                        $updateData['three_pc'] = ($rank[0] - 1) * 10 + $rank['1'];

                                        self::writeKeywordsQuery($db, $vo, $res, $rank, 'three_pc');
                                    }

                                    // 搜狗移动
                                    $res = curlPost($sogouMobileUrl, [
                                        'key' => $token,
                                        'domain' => $vo['url'],
                                        'keyword' => $vo['name']
                                    ])['data'];

                                    Log::info($vo['name'] . ' 搜狗移动 res>>>>>>>:' . $res);

                                    $res = json_decode($res, true);
                                    if (!empty($res['Result']['Ranks'])) {
                                        $rank = explode('-', $res['Result']['Ranks']['0']['RankStr']);
                                        $updateData['sougou_mob'] = ($rank[0] - 1) * 10 + $rank['1'];

                                        self::writeKeywordsQuery($db, $vo, $res, $rank, 'sougou_mob');
                                    }

                                    $db->update(env('database.prefix') . 'keyword')->cols($updateData)->where('id=' . $vo['id'])->query();
                                }
                            }
                        } catch (\Exception $e) {
                            Log::error($e->getMessage() . '>>>>>>
                        ' . $e->getTraceAsString());
                        }
                        Log::info('执行结束');
                    }
                });

            }
            /*************************************** 站长之家排名结束 ************************************************/
        };

        if (strtoupper(substr(PHP_OS,0,3))==='WIN') {
            Worker::runAll();
        }
    }

    protected static function writeKeywordsQuery($db, $vo, $res, $rank, $engine)
    {
        $db->insert(env('database.prefix') . 'keyword_query')->cols([
            'keyword_id' => $vo['id'],
            'seller_id' => $vo['seller_id'],
            'website_id' => $vo['website_id'],
            'keyword' => $vo['name'],
            'search_engine' => $engine,
            'collect_count' => isset($res['Result']['SiteCount']) ? $res['Result']['SiteCount'] : 0,
            'top_rank' => ($rank[0] - 1) * 10 + $rank['1'],
            'create_time' => time(),
            'page_title' => $res['Result']['Ranks']['0']['Title'] ?? '',
            'page_url' => $res['Result']['Ranks']['0']['Url'] ?? '',
        ])->query();
    }
}
